package com.tanglongan.designPattern.dp06_adapter.demo03.optimize02;

import com.tanglongan.designPattern.dp06_adapter.demo03.IPasswordForThird;
import com.tanglongan.designPattern.dp06_adapter.demo03.oldSystem.ResultMsg;

/**
 * 适配器实现
 */
public class PasswordForThirdAdapterV2 implements IPasswordForThird {

    @Override
    public ResultMsg loginForQQ(String openId) {
        return processLogin(openId, LoginForQQAdapter.class);
    }

    @Override
    public ResultMsg loginForWeChat(String openId) {
        return processLogin(openId, LoginForWeChatAdapter.class);
    }

    @Override
    public ResultMsg loginForToken(String openId) {
        return processLogin(openId, LoginForTokenAdapter.class);
    }

    @Override
    public ResultMsg loginForTelphone(String phone, String code) {
        return processLogin(phone, LoginForTelAdapter.class);
    }

    private ResultMsg processLogin(String id, Class<? extends ILoginAdapter> clazz) {
        try {
            ILoginAdapter adapter = clazz.newInstance();
            if (adapter.support(adapter)) {
                return adapter.login(id, adapter);
            }
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}
